#!/bin/bash
# Linux 双网卡绑定自动化脚本（自动获取网卡及网络参数，可交互指定）

BOND_IFACE="bond0"
BOND_MODE="1"   # 1=active-backup, 0=balance-rr, 4=802.3ad等
BOND_MIIMON="100"

# 自动获取前两块物理网卡
IFACES=($(ls /sys/class/net | grep -vE 'lo|bond|vir|br|docker|vnet' | head -2))
IFACE1="${IFACES[0]}"
IFACE2="${IFACES[1]}"

if [[ -z "$IFACE1" || -z "$IFACE2" ]]; then
    echo "未检测到两块物理网卡，请检查！"
    exit 1
fi

echo "检测到网卡: $IFACE1, $IFACE2"

# 获取当前主网卡网络配置
CUR_IP=$(ip -4 addr show $IFACE1 | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | head -1)
CUR_MASK=$(ip -4 addr show $IFACE1 | grep -oP '(?<=inet\s)\d+(\.\d+){3}/\d+' | awk -F'/' '{print $2}' | head -1)
CUR_GATEWAY=$(ip route | grep default | grep $IFACE1 | awk '{print $3}' | head -1)
CUR_DNS=$(grep ^nameserver /etc/resolv.conf | awk '{print $2}' | head -1)

# 掩码转换（CIDR转255.255.255.0格式）
cidr2mask() {
    local i mask=""
    local full_octets=$(($1/8))
    local part_octet=$(($1%8))
    for ((i=0;i<4;i++)); do
        if [ $i -lt $full_octets ]; then
            mask+=255
        elif [ $i -eq $full_octets ]; then
            mask+=$((256 - 2**(8-$part_octet)))
        else
            mask+=0
        fi
        [ $i -lt 3 ] && mask+=.
    done
    echo $mask
}

if [[ -n "$CUR_MASK" ]]; then
    CUR_NETMASK=$(cidr2mask $CUR_MASK)
else
    CUR_NETMASK="255.255.255.0"
fi

# 交互式参数
read -p "Bond IP [$CUR_IP]: " BOND_IP
BOND_IP=${BOND_IP:-$CUR_IP}

read -p "Bond Netmask [$CUR_NETMASK]: " BOND_NETMASK
BOND_NETMASK=${BOND_NETMASK:-$CUR_NETMASK}

read -p "Bond Gateway [$CUR_GATEWAY]: " BOND_GATEWAY
BOND_GATEWAY=${BOND_GATEWAY:-$CUR_GATEWAY}

read -p "Bond DNS [$CUR_DNS]: " BOND_DNS
BOND_DNS=${BOND_DNS:-$CUR_DNS}

# 加载bonding模块
modprobe bonding
echo "bonding" >> /etc/modules-load.d/bonding.conf

# 配置bond主接口
cat > /etc/sysconfig/network-scripts/ifcfg-${BOND_IFACE} <<EOF
DEVICE=${BOND_IFACE}
NAME=${BOND_IFACE}
TYPE=Bond
BONDING_MASTER=yes
BOOTPROTO=static
IPADDR=${BOND_IP}
NETMASK=${BOND_NETMASK}
GATEWAY=${BOND_GATEWAY}
DNS1=${BOND_DNS}
ONBOOT=yes
BONDING_OPTS="mode=${BOND_MODE} miimon=${BOND_MIIMON}"
EOF

# 配置从接口
for IFACE in $IFACE1 $IFACE2; do
cat > /etc/sysconfig/network-scripts/ifcfg-${IFACE} <<EOF
DEVICE=${IFACE}
NAME=${IFACE}
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=${BOND_IFACE}
SLAVE=yes
EOF
done

echo "重启网络服务..."
systemctl restart network

echo "Bonding 配置完成，请用 'cat /proc/net/bonding/${BOND_IFACE}' 检查状态。"